#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include "FMODSystem.h"
#include "FMODSound.h"
#include "BPMDetection.h"

#define DELTA_FREQUENCY 100
#define DELTA_ERROR     5000

using namespace std;

int main()
{
    try
    {
		FMODSystem sys;
		sys.init();
		FMODSound sound(&sys, "always.mp3");
		sound.play();

		float initialFreq = sound.getFrequency();
		float currentFreq = initialFreq;
		float targetFreq = initialFreq;
		printf("Frequency: %f\n", initialFreq);

		clock_t begin = 0;
		double tempo = 0;

		//list<double> reference_tempo;

		char input;
		while((input = getch()) != 'q')
		{
			switch(input)
			{
				case '-':
					sound.setFrequency(sound.getFrequency() - DELTA_FREQUENCY);
				break;
				case '+':
					sound.setFrequency(sound.getFrequency() + DELTA_FREQUENCY);
				break;
				case ' ':
					clock_t end = clock();
					if(begin != 0)
					{
						tempo = (float)(end - begin) / (float)CLOCKS_PER_SEC;
						begin = end;

						/// Calculate beat per minute
						/// based on the last lapse
						float bpm = 60 / tempo;
						targetFreq = (bpm * initialFreq) / 170;
						/*
						if(abs((int)(newFreq - currentFreq)) > DELTA_ERROR)
						{
							printf("BPM: %f - Frequency: %f \n", bpm, newFreq);
							currentFreq = newFreq;
							sound.setFrequency(newFreq);
						}
						*/
					}
					else
					{
						begin = end;
					}

					/// Slowly (or not) slide to the input rythm
					if(abs((int)(targetFreq - currentFreq)) > DELTA_FREQUENCY * 2)
					{
						if(targetFreq > currentFreq) currentFreq += DELTA_FREQUENCY;
						if(targetFreq < currentFreq) currentFreq -= DELTA_FREQUENCY;
						sound.setFrequency(currentFreq);
						printf("Current: %f \n", currentFreq);
					}
				break;
			}

			printf("Frequency: %f\n", sound.getFrequency());
		}

		return 0;
    }
    catch(Exception e)
    {
		printf("Error: %s\n", e.getMessage());
	}
}
